package com.coderyeah.cosmetology.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.coderyeah.cosmetology.entity.Image;
import com.coderyeah.cosmetology.mapper.ImageMapper;
import com.coderyeah.cosmetology.service.ImageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coderyeah.cosmetology.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lqs
 * @since 2022-05-24
 */
@Service
public class ImageServiceImpl extends ServiceImpl<ImageMapper, Image> implements ImageService {
    @Autowired
    private ImageMapper imageMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryAllByType(String type) {
        //先从redis查找数据 若未命中则查询数据库
        String key = "CACHE:IMAGE:" + type;
        String s = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(s)) {//存在
            List<Image> images = JSONUtil.toList(s, Image.class);
            return Result.success(images);
        }

        //查询数据库
        LambdaQueryWrapper<Image> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Image::getImagetype, type);
        List<Image> images = imageMapper.selectList(wrapper);

        //存入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(images), 30, TimeUnit.MINUTES);
        return Result.success(images);
    }

    @Override
    public Result queryById(Integer id) {
        Image image = imageMapper.selectById(id);
        return Result.success(image);
    }
}
